import 'dart:convert';

import 'package:get/get.dart';
import 'package:juming_test/action/home_action.dart';
import 'package:juming_test/config/global_storage_key.dart';
import 'package:juming_test/model/home/home_kingkong_model.dart';
import 'package:juming_test/model/home/kingkong_management_section_model.dart';
import 'package:logger/logger.dart';
import 'package:shared_preferences/shared_preferences.dart';

class HomeKingkongViewModel extends GetxController {
  // 默认数据
  late final List<KingkongManagementSectionModel> _defaultSections;

  // 编辑状态临时存储数据
  final Rx<List<KingkongManagementSectionModel>> editSections = Rx([]);

  // 常态使用数据
  final Rx<List<KingkongManagementSectionModel>> normalSections = Rx([]);
  // 首页金刚位展示数据
  final Rx<List<HomeKingkongModel>> normalList = Rx([]);

  final Logger _logger = Logger();

  @override
  Future<void> onReady() async {
    super.onReady();
    await _getHomeKingkongList();
  }

  // 添加项目到激活列表
  void addToActive(HomeKingkongModel item) {
    final editActiveSection = editSections.value.first;
    var editInactiveList = editSections.value.sublist(1);
    // 从未激活列表中移除
    editInactiveList.removeWhere((section) {
      section.items.removeWhere((element) => element.id == item.id);
      return section.items.isEmpty;
    });
    editSections.value.removeWhere((section) => section.items.isEmpty);
    // 添加到首页列表
    if (editActiveSection.items.any((element) => element.id == item.id)) {
      return;
    }
    editActiveSection.items.add(item);
    editSections.refresh();
  }

  // 移除激活项目
  void removeFromActive(HomeKingkongModel item) {
    final editActiveSection = editSections.value.first;
    final editInactiveList = editSections.value.sublist(1);

    editActiveSection.items.remove(item);
    // 添加到原模块,未找到section的话就新增一个
    try {
      final section = editInactiveList.firstWhere(
        (section) => section.id == item.sectionId,
      );
      section.items.add(item);
      section.items.sort((a, b) => a.sort.compareTo(b.sort));
    } catch (e) {
      _logger.d("未找到sectionId${item.sectionId}，新建一个section");
      // 创建一个section
      final newSection = KingkongManagementSectionModel(
        item.sectionId,
        item.sectionSort,
        item.sectionTitle,
        [item],
      );
      editSections.value.add(newSection);
      editSections.value.sort((a, b) => a.sort.compareTo(b.sort));
    }
    editSections.refresh();
  }

  // 获取首页金刚位数据
  Future<void> _getHomeKingkongList() async {
    final prefs = await SharedPreferences.getInstance();
    final String? kingkongListString = prefs.getString(
      GlobalStorageKey.homeKingkongKey,
    );

    if (kingkongListString != null) {
      // 从本地获取
      final List<dynamic> kingkongListJson = jsonDecode(kingkongListString);
      normalList.value =
          kingkongListJson.map((e) => HomeKingkongModel.fromJson(e)).toList();
      _logger.i('从本地获取金刚位数据');
    } else {
      // 从 HomeAction 获取
      normalList.value = await HomeAction.fetchHomeKingkongList();
      _logger.i('从 HomeAction 获取金刚位数据');

      // 缓存到本地
      cacheKingkongList(normalList.value);
    }
  }

  // 缓存金刚位数据到本地
  Future<void> cacheKingkongList(List<HomeKingkongModel> kingkongList) async {
    normalList.value =
        kingkongList
            .map((item) => HomeKingkongModel.fromJson(item.toJson()))
            .toList();
    final prefs = await SharedPreferences.getInstance();
    final String kingkongListString = jsonEncode(kingkongList);
    prefs.setString(GlobalStorageKey.homeKingkongKey, kingkongListString);
  }

  // 获取全部金刚位数据
  Future<void> getAllKingkongList() async {
    List<KingkongManagementSectionModel> sections =
        await HomeAction.fetchAllKingkongList();

    // 初始化默认数据
    _defaultSections =
        sections
            .map(
              (section) =>
                  KingkongManagementSectionModel.fromJson(section.toJson()),
            )
            .toList();

    // normalSections数据
    normalSections.value = getSectionsByItems(normalList.value);
  }

  // 取默认数据中isDefault且按sort排序
  List<HomeKingkongModel> getDefaultItems() {
    return _defaultSections
        .map(
          (section) => section.items
              .where((item) => item.isDefault == true)
              .map((item) => HomeKingkongModel.fromJson(item.toJson())),
        )
        .expand((element) => element)
        .toList()
      ..sort((a, b) => a.sort.compareTo(b.sort));
  }

  // 通过默认数据组合当前数据源
  List<KingkongManagementSectionModel> getSectionsByItems(
    List<HomeKingkongModel> items,
  ) {
    List<KingkongManagementSectionModel> sections = [];
    sections =
        _defaultSections
            .map(
              (section) =>
                  KingkongManagementSectionModel.fromJson(section.toJson()),
            )
            .toList();
    sections.removeWhere((section) {
      section.items.removeWhere(
        (element) => items.any((item) => item.id == element.id),
      );
      return section.items.isEmpty;
    });
    final item = items.first;
    final firstSection = KingkongManagementSectionModel(
      item.sectionId,
      item.sectionSort,
      item.sectionTitle,
      items,
    );
    sections.insert(0, firstSection);
    return sections;
  }
}
